package server;

import java.io.InputStream;
import java.io.OutputStream;
import java.net.ServerSocket;
import java.net.Socket;

public class V2BootStrap {

    private int port = 8080;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    public static void main(String[] args) {
        V2BootStrap server = new V2BootStrap();
        server.start();
    }


    public void start(){
        //完成1.0版本
        //请求localhost:8082,返回hello minicat
        //封装Request和Response对象
        try{
            ServerSocket serverSocket = new ServerSocket(port);
            System.out.println("=====>>>Minicat start on port：" + port);
            while(true){
                //阻塞在这里
                Socket socket = serverSocket.accept();
                InputStream inputStream = socket.getInputStream();
                int count = 0;
                while(count == 0){
                    count = inputStream.available();
                }

                byte[] bytes = new byte[count];
                inputStream.read(bytes);
                String inputStr = new String(bytes);
                System.out.println("接受:"+inputStr);

                OutputStream outputStream = socket.getOutputStream();
                String data = "Hello MiniCat";
                String result = HttpProtocolUtil.getHttpHeader200(data.getBytes().length)+data;
                outputStream.write(result.getBytes());
                socket.close();
            }

        }catch (Exception e){
            e.printStackTrace();
        }

    }
}
